<div class="container">
    <h1 id="pkg-overview">package httptest</h1>
    <p><code>import "net/http/httptest"</code>
    </p><p>httptest包提供了HTTP测试的常用函数。</p>
    
    
		
        
        
        
        
        
        
    
    
    
		
        
        
        
    
    <h2 id="pkg-constants">Constants </h2>
    <pre>const <span id="DefaultRemoteAddr">DefaultRemoteAddr</span> = "1.2.3.4"</pre>
    <p>DefaultRemoteAddr是默认的远端地址。如果ResponseRecorder未显式的设置该属性，RemoteAddr方法就会返回该值。</p>
    <h2 data-kind="f" id="NewRequest">func <a href="https://github.com/golang/go/blob/master/src//net/http/httptest/httptest.go#L41" title="View Source">NewRequest</a>  </h2>
    
    <p>NewRequest 返回一个新的服务器访问请求，这个请求可以传递给 http.Handler 以便进行测试。</p>
    <p>target 参数的值为 <a href="http://tools.ietf.org/html/rfc7230">RFC 7230</a> 中提到的“请求目标”（request-target)： 它可以是一个路径或者一个绝对 URL。如果 target 是一个绝对 URL，那么 URL 中的主机名（host name）将被使用；否则主机名将为 example.com。</p>
    <p>当 target 的模式为 https 时，TLS 字段的值将被设置为一个非 nil 的随意值（dummy value）。</p>
    <p>Request.Proto 总是为 HTTP/1.1。</p>
    <p>如果 method 参数的值为空， 那么使用 GET 方法作为默认值。</p>
    <p>body 参数的值可以为 nil；另一方面，如果 body 参数的值为 *bytes.Reader 类型、 *strings.Reader 类型或者 *bytes.Buffer 类型，那么 Request.ContentLength 将被设置。</p>
    <p>为了使用的方便，NewRequest 将在 panic 可以被接受的情况下，使用 panic 代替错误。</p>
    <p>如果你想要生成的不是服务器访问请求，而是一个客户端 HTTP 请求，那么请使用 net/http 包中的 NewRequest 函数。</p>
    <h2 id="ResponseRecorder">type <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#15" title="View Source">ResponseRecorder</a> </h2>
    <pre>type ResponseRecorder struct {
    <span id="ResponseRecorder.Code">Code</span>      <a href="builtin.htm#int">int</a>           <span class="com">// HTTP回复的状态码</span>
    <span id="ResponseRecorder.HeaderMap">HeaderMap</span> <a href="net/http.htm">http</a>.<a href="net/http.htm#Header">Header</a>   <span class="com">// HTTP回复的头域</span>
    <span id="ResponseRecorder.Body">Body</span>      *<a href="bytes.htm">bytes</a>.<a href="bytes.htm#Buffer">Buffer</a> <span class="com">// 如非nil，会将Write方法写入的数据写入bytes.Buffer</span>
    <span id="ResponseRecorder.Flushed">Flushed</span>   <a href="builtin.htm#bool">bool</a>
    <span class="com">// 内含隐藏或非导出字段</span>
}</pre>
    <p>ResponseRecorder实现了http.ResponseWriter接口，它记录了其修改，用于之后的检查。</p>
    <div class="panel-group">
        <div class="panel panel-default" id="example-ResponseRecorder">
            <div class="panel-heading" onclick="document.getElementById('ex-ResponseRecorder').style.display = document.getElementById('ex-ResponseRecorder').style.display=='none'?'block':'none';">Example</div>
            <div class="panel-collapse collapse" id="ex-ResponseRecorder">
                <div class="panel-body">
                    <pre>handler := func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "something failed", http.StatusInternalServerError)
}
req, err := http.NewRequest("GET", "http://example.com/foo", nil)
if err != nil {
    log.Fatal(err)
}
w := httptest.NewRecorder()
handler(w, req)
fmt.Printf("%d - %s", w.Code, w.Body.String())</pre>
                    <p>Output:
                    </p><pre>500 - something failed
</pre>
                </div>
            </div>
        </div>
    </div>
    <h3 id="NewRecorder">func <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#25" title="View Source">NewRecorder</a> </h3>
    <pre class="funcdecl">func NewRecorder() *<a href="#ResponseRecorder">ResponseRecorder</a></pre>
    <p>NewRecorder返回一个初始化了的ResponseRecorder.</p>
    <h3 id="ResponseRecorder.Flush">func (*ResponseRecorder) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#67" title="View Source">Flush</a> </h3>
    <pre class="funcdecl">func (rw *<a href="#ResponseRecorder">ResponseRecorder</a>) Flush()</pre>
    <p>Flush将rw.Flushed设置为真。</p>
    <h3 id="ResponseRecorder.Header">func (*ResponseRecorder) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#38" title="View Source">Header</a> </h3>
    <pre class="funcdecl">func (rw *<a href="#ResponseRecorder">ResponseRecorder</a>) Header() <a href="net/http.htm">http</a>.<a href="net/http.htm#Header">Header</a></pre>
    <p>Header返回回复的头域，即Header字段。</p>
    <h3 class="" data-kind="m" id="ResponseRecorder.Result">func (*ResponseRecorder) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go#L162" title="View Source">Result</a>  </h3>
    
    <p>Result 返回处理器生成的响应。</p>
    <p>处理器返回的响应至少会对状态码（StatusCode）、首部（Header）、主体（Body）以及可选的 Trailer 进行设置。 因为未来可能会有更多字段被设置，所以用户不应该在测试里面对结果调用 DeepEqual。</p>
    <p>Response.Header 是写入操作第一次调用时的首部快照（snapshot of the headers）； 另一方面， 如果处理器没有执行过写入操作， 那么 Response.Header 就是 Result 方法调用时的首部快照。</p>
    <p>Response.Body 将被生成为一个非 nil 值，而 Body.Read 则保证不会返回除 io.EOF 之外的其他任何错误。</p>
    <p>Result 必须在处理器执行完毕之后调用。</p>
    <h3 id="ResponseRecorder.Write">func (*ResponseRecorder) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#48" title="View Source">Write</a> </h3>
    <pre class="funcdecl">func (rw *<a href="#ResponseRecorder">ResponseRecorder</a>) Write(buf []<a href="builtin.htm#byte">byte</a>) (<a href="builtin.htm#int">int</a>, <a href="builtin.htm#error">error</a>)</pre>
    <p>Write总是成功，如果rw.Body非nil会把数据写入该字段。</p>
    <h3 id="ResponseRecorder.WriteHeader">func (*ResponseRecorder) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/recorder.go?name=release#59" title="View Source">WriteHeader</a> </h3>
    <pre class="funcdecl">func (rw *<a href="#ResponseRecorder">ResponseRecorder</a>) WriteHeader(code <a href="builtin.htm#int">int</a>)</pre>
    <p>WriteHeader设置rw.Code。</p>
    <h3 data-kind="m" id="ResponseRecorder.WriteString">func (*ResponseRecorder) <a href="https://golang.org/src/net/http/httptest/recorder.go#L107" title="View Source">WriteString</a>  </h3>
    
    <p>在 str 不为 nil 的情况下， WriteString 总会成功地将 buf 中的内容写入到 rw.Body 当中。</p>
    <h2 id="Server">type <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#21" title="View Source">Server</a> </h2>
    <pre>type Server struct {
    <span id="Server.URL">URL</span>      <a href="builtin.htm#string">string</a> <span class="com">// 格式为http://ipaddr:port，没有末尾斜杠的基地址</span>
    <span id="Server.Listener">Listener</span> <a href="net.htm">net</a>.<a href="net.htm#Listener">Listener</a>
    <span class="com">// TLS是可选的TLS配置，在TLS开始后会填写为新的配置。</span>
    <span class="com">// 如果在未启动的Server调用StartTLS方法前设置，已经存在的字段会拷贝进新配置里。</span>
    <span id="Server.TLS">TLS</span> *<a href="crypto/tls.htm">tls</a>.<a href="crypto/tls.htm#Config">Config</a>
    <span class="com">// Config可能会在调用Start/StartTLS方法之前调用NewUnstartedServer时被修改。</span>
    <span id="Server.Config">Config</span> *<a href="net/http.htm">http</a>.<a href="net/http.htm#Server">Server</a>
    <span class="com">// 内含隐藏或非导出字段</span>
}</pre>
    <p>Server是一个HTTP服务端，在本地环回接口的某个系统选择的端口监听，用于点对点HTTP测试。</p>
    <div class="panel-group">
        <div class="panel panel-default" id="example-Server">
            <div class="panel-heading" onclick="document.getElementById('ex-Server').style.display = document.getElementById('ex-Server').style.display=='none'?'block':'none';">Example</div>
            <div class="panel-collapse collapse" id="ex-Server">
                <div class="panel-body">
                    <pre>ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
res, err := http.Get(ts.URL)
if err != nil {
    log.Fatal(err)
}
greeting, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("%s", greeting)</pre>
                    <p>Output:
                    </p><pre>Hello, client
</pre>
                </div>
            </div>
        </div>
    </div>
    <h3 id="NewServer">func <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#82" title="View Source">NewServer</a> </h3>
    <pre class="funcdecl">func NewServer(handler <a href="net/http.htm">http</a>.<a href="net/http.htm#Handler">Handler</a>) *<a href="#Server">Server</a></pre>
    <p>NewServer返回一个新的、已启动的Server。调用者必须在用完时调用Close方法关闭它。</p>
    <h3 id="NewTLSServer">func <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#158" title="View Source">NewTLSServer</a> </h3>
    <pre class="funcdecl">func NewTLSServer(handler <a href="net/http.htm">http</a>.<a href="net/http.htm#Handler">Handler</a>) *<a href="#Server">Server</a></pre>
    <p>NewTLSServer返回一个新的、使用TLS的、已启动的Server。调用者必须在用完时调用Close方法关闭它。</p>
    <h3 id="NewUnstartedServer">func <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#94" title="View Source">NewUnstartedServer</a> </h3>
    <pre class="funcdecl">func NewUnstartedServer(handler <a href="net/http.htm">http</a>.<a href="net/http.htm#Handler">Handler</a>) *<a href="#Server">Server</a></pre>
    <p>NewUnstartedServer返回一个新的、未启动的Server。在修改其配置后，调用者应该调用Start或StartTLS启动它；调在用完时用者必须调用Close方法关闭它。</p>
<h3 id="Server.Start">func (*Server) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#102" title="View Source">Start</a> </h3>
    <pre class="funcdecl">func (s *<a href="#Server">Server</a>) Start()</pre>
    <p>Start启动NewUnstartedServer返回的服务端。</p>
    <h3 id="Server.StartTLS">func (*Server) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#117" title="View Source">StartTLS</a> </h3>
    <pre class="funcdecl">func (s *<a href="#Server">Server</a>) StartTLS()</pre>
    <p>StartTLS启动NewUnstartedServer函数返回的服务端的TLS监听。</p>
    <h3 id="Server.CloseClientConnections">func (*Server) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#177" title="View Source">CloseClientConnections</a> </h3>
    <pre class="funcdecl">func (s *<a href="#Server">Server</a>) CloseClientConnections()</pre>
    <p>CloseClientConnections关闭当前任何与该服务端建立的HTTP连接。</p>
    <h3 id="Server.Close">func (*Server) <a href="https://github.com/golang/go/blob/master/src/net/http/httptest/server.go?name=release#166" title="View Source">Close</a> </h3>
    <pre class="funcdecl">func (s *<a href="#Server">Server</a>) Close()</pre>
    <p>Close关闭服务端，并阻塞直到所有该服务端未完成的请求都结束为止。</p>
</div>